package com.bolt.report.engine.export.html;

import com.bolt.report.engine.fill.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Writer;

public class HtmlExporterVisitor implements ExporterVisitor<HtmlExporter> {
    private Logger logger = LoggerFactory.getLogger(HtmlExporterVisitor.class);

    private HyperlinkHtmlBuilder hyperlinkHtmlBuilder = new DefaultHyperlinkHtmlBuilder();

    @Override
    public void visit(FillTextElement textElement, HtmlExporter exporter) {
        String text = buildLinkContext(textElement, textElement.getValue());
        printContext(exporter, text);
    }

    @Override
    public void visit(FillDataSetElement dataSetElement, HtmlExporter exporter) {
        String text = buildLinkContext(dataSetElement, dataSetElement.getValue());
        printContext(exporter, text);
    }

    public void printContext(HtmlExporter exporter, String text) {
        try {
            Writer out = exporter.getExporterOutput().getWriter();
            out.write(text);
        } catch (Exception ex) {
            logger.error("exporter html error", ex);
        }
    }

    public String buildLinkContext(BaseFillElement<String> element, String text) {
        if (element.haveHyperlink()) {
            return hyperlinkHtmlBuilder.build(element, text);
        } else {
            return text;
        }
    }

    @Override
    public void visit(FillChartElement chartElement, HtmlExporter exporter) {
        StringBuilder html = new StringBuilder();
        if (exporter.containsParam(chartElement.getChartId())) {
            html.append("<img src=\"" + exporter.getParameter(chartElement.getChartId()) + "\"/>");
        } else {
            html.append("<div class=\"chart\" id=\"" + chartElement.getChartId() + "\"  style=\"width:" + chartElement.getWidth() + "px !important;height:" + chartElement.getHeight() + "px !important\"></div>");
            html.append("<script> $(document).ready(function(){refreshChart(" + chartElement.getValue() + ");})</script>");
        }
        String text = buildLinkContext(chartElement, html.toString());
        printContext(exporter, text);
    }

    @Override
    public void visit(FillImageElement imageElement, HtmlExporter exporter) {
        StringBuilder html = new StringBuilder();
        html.append("<img src=\"" + imageElement.getValue() + "\" style=\"width:" + imageElement.getWidth() + "px !important;height:" + imageElement.getHeight() + "px !important\"/>");
        String text = buildLinkContext(imageElement, html.toString());
        printContext(exporter, text);
    }

    @Override
    public void visit(FillCodeImageElement barCodeElement, HtmlExporter exporter) {
        visit((FillImageElement) barCodeElement, exporter);
    }
}